package com.example.canteen.dao.impl;

import com.example.canteen.dao.AdminDao;
import com.example.canteen.domain.Admin;
import com.example.canteen.util.JDBCUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class AdminDaoImpl implements AdminDao {
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
    @Override
    public Admin findById(int id) {
        Admin admin = null;
        String sql = "SELECT id,PASSWORD,NAME,phone,sex FROM admin WHERE id=?";
        try{
            admin =template.queryForObject(sql,new BeanPropertyRowMapper<Admin>(Admin.class),id);
        }catch(Exception e){

        }
        return admin;
    }

    @Override
    public List<Admin> findAll() {
        String sql = "SELECT id,PASSWORD,NAME,phone,sex FROM admin";
        return template.query(sql, new BeanPropertyRowMapper<Admin>(Admin.class));
    }

    @Override
    public int delete(int id) {
        String sql = "DELETE FROM admin WHERE id=?";
        return template.update(sql,id);
    }

    @Override
    public void save(Admin admin) {
        String sql = "insert into admin(id,PASSWORD,NAME,phone,sex) value(?,?,?,?,?)";
        template.update(sql,admin.getId(),
                admin.getPassword(),
                admin.getName(),
                admin.getPhone(),
                admin.getSex());
    }

    @Override
    public int update(Admin admin) {
        String sql = "UPDATE admin SET PASSWORD=?,NAME=?,sex=?,phone=? WHERE id=?";
        return template.update(sql, admin.getPassword(),
                admin.getName(),
                admin.getSex(),
                admin.getPhone(),
                admin.getId());
    }

    @Override
    public Admin findByUsernameAndPassword(int id, String password) {
        Admin admin = null;
        String sql = "SELECT id,PASSWORD,NAME,sex,phone FROM admin WHERE id=? and password=?";
        try {
            admin =template.queryForObject(sql,new BeanPropertyRowMapper<Admin>(Admin.class),id,password);
        }catch (Exception e){

        }
        return admin;

    }
}
